package com.baizhi.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import java.util.Properties;

@EnableWebMvc
@ComponentScan("com.baizhi.controller")
public class SpringmvcConfig implements WebMvcConfigurer {

    /**
     * 配置拦截器
     * @param registry
     */
//    @Override
//    public void addInterceptors(InterceptorRegistry registry) {
//        registry.addInterceptor(new LoginInterceptor())
//                .addPathPatterns("/**")         //拦截所有资源 ，配置黑名单
//                .excludePathPatterns("/admin/add.do","/admin/login.do","/loginHandler.do","/regist.do");          //对**放行，配置白名单
//    }

    /**
     * 配置视图解析器
     */
    @Bean
    public InternalResourceViewResolver createViewResolver(){
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/views/");
        viewResolver.setSuffix(".html");
        return viewResolver;
    }


    /**
     * 配置文件上传处理器
     */
    @Bean("multipartResolver")
    public MultipartResolver createMultipartResolver(){
        CommonsMultipartResolver cmr = new CommonsMultipartResolver();
        cmr.setDefaultEncoding("UTF-8");
        cmr.setMaxUploadSize(1024*10*5);
        return cmr;
    }

    /**
     * 配置全局异常处理器
     */
    @Bean
    public SimpleMappingExceptionResolver createSimpleMappingExceptionResolver(){
        /*
         <prop key="java.lang.ArrayIndexOutOfBoundsException">err1</prop>
         <prop key="java.lang.NullPointerException">err2</prop>
         <prop key="java.lang.Throwable">error2</prop>
         */
        SimpleMappingExceptionResolver smer = new SimpleMappingExceptionResolver();
        Properties properties = new Properties();
        properties.setProperty("java.lang.ArrayIndexOutOfBoundsException","err01");
        properties.setProperty("java.lang.NullPointerException","err2");
        properties.setProperty("java.lang.Throwable","err");
        smer.setExceptionMappings(properties);
        return smer;
    }
}
